/**
 * 
 * @authors youzhao.zhou@pandauu.com
 * @date    2016-09-22 13:31:58
 * @version $Id$
 * 
 * 渲染消息
 * 添加单条消息
 * 
 * 
 */

;(function(root,factory){

  if(typeof exports === 'object' && typeof module === 'object'){
    
    module.exports = factory(exports,typeof exports !== 'undefined' ? require('./zepto.js')&&root.$ : root.$, require('../../public_src/js/1_self/3_log.js'), require('../../public_src/js/1_self/2_config.js'));

  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['exports','./zepto.js','../../public_src/js/1_self/3_log.js','../../public_src/js/1_self/2_config.js'], factory);
  } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
    // CommonJS
    module.exports = factory(exports,typeof exports !== 'undefined' ? require('./zepto.js')&&root.$ : root.$, require('../../public_src/js/1_self/3_log.js'), require('../../public_src/js/1_self/2_config.js'));
  } else {
    // Browser globals
    root.Project.prototype.getMsg = factory({}, root.$, root.log, root.conf);
  }
})(typeof window !== 'undefined' ? window : this ,function(exports, $, log, conf, undefined){
  'use strict';

  /*
    调试开关
  */
  log._logToggle(true);

  log._log(conf);
  var urlConf = conf._conf;

  function getMsg(_){
    /*
      获取历史消息
    */
    $.ajax({
      url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.msgList,
      type: 'GET',
      dataType: 'json',
      data: {
        thread_id : $('.service').data('id')
      }
    })
    .done(function(data) {
      if (data.code === 0) {
        for(var k in data.data){
          if (data.data[k].type === '1') {
            data.data[k].msg = setUrl(data.data[k].msg);
          }else{
            data.data[k].msg = urlConf.root + data.data[k].msg;
            data.data[k].thumb = data.data[k].msg.replace('uploads/kf/','uploads/kf/thumbnail/');
            //data.data[k].thumb = data.data[k].msg.replace('uploads/kf/','uploads/kf/');
          }
        }
        renderMsg(_, data.data);

        imgDefer();
      }
        
    })
    .fail(function() {
      log._log("error");
    })
    .always(function() {
      log._log("complete");
    });
    
    /*
      服务器推送消息
    */
    var sse = new EventSource(urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.sseKf + '?thread_id=' + $('.service').data('id'));

    sse.onmessage = function(data){
      log._log(data);
      var data = JSON.parse(data.data);
      if (typeof data !== 'undefined' && data.code === 0) {
        $('.has-msg').removeClass('s-hide');
        setTimeout(function(){
          $('.has-msg').addClass('s-hide');
        },2000);
        for(var k in data.data){
          if (data.data[k].type === '1') {

            data.data[k].msg = setUrl(data.data[k].msg);
          }else{
            data.data[k].msg = urlConf.root + data.data[k].msg;
            data.data[k].thumb = data.data[k].msg.replace('uploads/kf/','uploads/kf/thumbnail/');
            //data.data[k].thumb = data.data[k].msg.replace('uploads/kf/','uploads/kf/');
          }
          renderOneMsg(_, data.data);
          imgDefer();
        }
        
      }
      log._log(data);
      
    };
  }
  
  /*
    文字信息URL处理
  */
  function setUrl(str){
    /*
      验证是否带有请求头正则
    */
    var reg = /(http:\/\/|https:\/\/)/g;
    /*
      提取URL正则
    */
    var reg1 = /((http:\/\/|https:\/\/)(((\w|=|\?|\/|&|-)+)(\.)((\.|\w|=|\?|\/|&|-)+)))/g;
    var reg2 = /((\w|=|\?|\/|&|-)+)(\.)((\.|\w|=|\?|\/|&|-)+)/g;
    if (reg2.test(str)) {
      if (!reg.test(str)) {
        str = str.replace(str.match(reg2)[0], '<a class="url-style" href="' + "http://" + str.match(reg2)[0] + '">' + str.match(reg2)[0] + '</a>');
      }else{
        str = str.replace(reg1, '<a class="url-style" href="$1">$1</a>');
      }
    }

    log._log(str);
    return str;
  }

  /*
    渲染消息
  
  */
  function renderMsg(_, data){
    var msgItemTpl = $('#msgItemTpl');

    $('.chat-container').html(_.template(msgItemTpl.html())({list: data}));

    $('body')[0].scrollTop = $('.chat-container').height() + parseFloat($('.chat-container').css('padding-top')) + parseFloat($('.chat-container').css('padding-bottom')) - $(window).height();
  }
  /*
    单条渲染消息
  
  */
  function renderOneMsg(_, data){
    var msgItemTpl = $('#msgItemTpl');

    $('.chat-container').append(_.template(msgItemTpl.html())({list: data}));

    
    //$('body')[0].scrollTop = $('.chat-container').height() + parseFloat($('.chat-container').css('padding-top')) + parseFloat($('.chat-container').css('padding-bottom')) - $(window).height();
    
      
  }

  /*
    图片延时加载
  */

  function imgDefer(){
    var isDeferr = $('[data-deferr]').data('deferr');
    var doms = $('[data-deferr]');

    doms.each(function(index, el) {
      var self = this;
      var imgUrl = $(self).data('url');

      var img = new Image();

        img.onload = function(){
          $(self).parent().removeClass('img-start');

          if (img.height < 600) {
            $(self).parent().css({
              height : 'auto'
            });
          }
          $(self).attr({
            src : imgUrl
          });
        };

        img.src = imgUrl;
    });

  }

  window.addEventListener('unload',function(){
    log = null;
    $.ajax({
      url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.userLogout,
      type: 'GET',
      dataType: 'json'
    })
    .done(function() {
      log._log("success");
    })
    .fail(function() {
      log._log("error");
    })
    .always(function() {
      log._log("complete");
    });
    
  },false);

  return getMsg;
});